'use strict';

const Controller = require('egg').Controller;

const jwt = require('jsonwebtoken');

class HomeController extends Controller {
    async index() {
        const { ctx } = this;
        ctx.body = 'hi, egg';
    }
    async login(){
        let {ctx,service} = this;
        let {username,password} = ctx.request.body;


        let errors = this.app.validator.validate({username:{type: 'string', required: true, allowEmpty: false}, password:{type: 'password', required: true, allowEmpty: false, min: 6}},ctx.request.body);
        console.log("errors",errors)
        // if(errors.length>0){
        //     //没有通过校验

        // }else{

        // }


         if(username && password){
            
             let data = await service.home.login(username,password)
             if(data.length){
                 //登录成功
                 let token = jwt.sign({username,roleid:data[0].roleid},'1705b',{expiresIn:60*60})
                    ctx.body = {
                        code:1,
                        msg:'登录成功',
                        token
                    }
             }else{
                 ctx.body = {
                     code:0,
                     msg:'登录失败'
                 }
             }
         }
    }

    async registry(){
        //加密的密码

    }

    async del(){
        let {ctx,service} = this;
        let {id} = ctx.query;
        if(id){
            // let token = ctx.request.header.token;
            // let info = jwt.verify(token,'1705b');
            console.log("ctx.info",ctx.info)
            if(ctx.info.roleid === 1){
                //超级管理员  删
                try{
                    await service.home.del(id);
                    ctx.body = {
                        code:1,
                        msg:'删除成功'
                    }
                }catch(e){
                    ctx.body = {
                        code:0,
                        msg:e
                    }
                }
            }else{
                //不能删
                ctx.body = {
                    code:3,
                    msg:'没有权限'
                }
            }
        }else{
            ctx.body = {
                code:2,
                msg:'参数丢失'
            }
        }
    }
}

module.exports = HomeController;
